const { parkingSpaceModel } = require('../modules/parkingSpaceModel')

// 新增
async function addParkingSpace(req, res, next) {

    const data = req.body;
    await parkingSpaceModel.create(data);
    res.send({
        message: '新增车位成功',
        code: 200,

    })
}
// 获取所有的车位数据
async function getParkingSpace(req, res, next) {

    // 获取前端给后端的数据
    const { value, currentPage, pageSize } = req.query;
    //获取总条数
    const total = await parkingSpaceModel.find({
        $or: [
            { carportNumber: { $regex: value, $options: '$i' } },

        ]
    }).countDocuments();
    // console.log('total打印纸', total);
    // 获取总页数
    const pages = Math.ceil(total / pageSize);
    const result = await parkingSpaceModel.find({
        $or: [
            { carportNumber: { $regex: value, $options: '$i' } },

        ]
    })
        .populate('community_id')
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
    // console.log(result);
    if (result.length > 0) {
        res.send({
            message: '车位数据获取成功',
            code: 200,
            data: { result, total, pages }
        })
    } else {
        res.send({
            message: '车位数据获取失败',
            code: 200,

        })
    }

}
// 删除
async function deleteParkingSpace(req, res, next) {
    const _id = req.body;
    await parkingSpaceModel.deleteOne({ _id })
    res.send({
        message: '删除成功',
        code: 200
    })
}
// 传入一个小区id，获取这个小区下面的所有的车位
async function getParkingSpaceByID(req, res, next) {
    const community_id = req.params;
    const result = await parkingSpaceModel.find({ community_id })
    res.send({
        message: '获取小区车位成功',
        code: 200,
        result
    })
}

// 获取要修改的车位数据
async function getamendParkingSpaceID(req, res, next) { 
    const _id= req.query;
    const result=await parkingSpaceModel.find(_id).populate('community_id')
    if(result.length>0){
        res.send({
            message:'获取数据成功',
            code:200,
            result
        })
    }else{
        res.send({
            message:'获取数据失败',
            code:500
        })
    }
}

async function amendParkingSpace(req, res, next){
    const data=req.body;
    console.log(data);
    const result=await parkingSpaceModel.updateOne({_id:data._id},data);
    if (result.nModified > 0) {
		res.send({
			message: '数据修改成功',
			code: 200,
		})
	} else {
		res.send({
			message: '数据修改失败',
			code: 500,
		})
	}
}




module.exports = { addParkingSpace, getParkingSpace, deleteParkingSpace, 
    getParkingSpaceByID, getamendParkingSpaceID ,amendParkingSpace}